<?php

/**
 * 创建模板
 */
if($uri == "/api/admin/template/create"){
    $postJson = json_decode(file_get_contents("php://input"));
    $name = $postJson->name;
    $pictures_count = $postJson->pictures_count;
    $sample_data = $postJson->sample_data;
    $input_structure = $postJson->input_structure;
    $regex = $postJson->regex;
    $template_data = $postJson->template_data;
    $switch_reasons = $postJson->switch_reasons;
    $category_id = $postJson->category_id;
    $regex = str_replace('\\', '\\\\', $regex);
    $template_data = str_replace('\\', '\\\\', $template_data);
    $price = isset($postJson->price) ? intval($postJson->price) : 0; // 添加价格字段
    $user_task_limit = isset($postJson->user_task_limit) ? intval($postJson->user_task_limit) : 0;
    $duration = isset($postJson->duration) ? intval($postJson->duration) : 0;
    $is_open = isset($postJson->is_open) ? intval($postJson->is_open) : 0;
    // 验证模板名称
    if(empty($name)) {
        $outJson->msg = "模板名称不能为空";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 检查名称长度
    if(mb_strlen($name) > 32) {
        $outJson->msg = "模板名称不能超过32个字符";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 验证图片数量
    if(!is_numeric($pictures_count) || $pictures_count < 0 || $pictures_count > 999) {
        $outJson->msg = "图片数量必须是0-999之间的数字";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 防SQL注入
    $name = addslashes($name);
    
    // 验证输入结构是否为有效JSON
    if(!empty($input_structure)) {
        json_decode($input_structure);
        if(json_last_error() !== JSON_ERROR_NONE) {
            $outJson->msg = "输入结构必须是有效的JSON格式";
            $outJson->code = 400;
            echo json_encode($outJson);
            exit;
        }
    }

    // 验证切换原因是否为有效JSON
    if(!empty($switch_reasons)) {
        json_decode($switch_reasons);
        if(json_last_error() !== JSON_ERROR_NONE) {
            $outJson->msg = "切换原因必须是有效的JSON格式";
            $outJson->code = 400;
            echo json_encode($outJson);
            exit;
        }
    }

    $sql_id = $cnSql->insert_json("templates", array(
        'name' => $name,
        'pictures_count' => $pictures_count,
        'sample_data' => $sample_data,
        'category_id' => $category_id,
        'input_structure' => $input_structure,
        'switch_reasons' => $switch_reasons, // 添加切换原因
        'regex' => $regex,
        'duration' => $duration,
        'template_data' => $template_data,
        'price' => $price, // 添加价格字段
        'is_open' => $is_open,
        'user_task_limit' => $user_task_limit // 添加任务次数限制
    ));

    if($sql_id) {
        $outJson->msg = "模板创建成功";
        $outJson->code = 200;
    } else {
        $outJson->msg = "模板创建失败";
        $outJson->data =  array(
            'name' => $name,
            'pictures_count' => $pictures_count,
            'sample_data' => $sample_data,
            'category_id' => $category_id,
            'input_structure' => $input_structure,
            'regex' => $regex,
            'duration' => $duration,
            'template_data' => $template_data,
            'price' => $price, // 添加价格字段
            'is_open' => $is_open,
            'user_task_limit' => $user_task_limit // 添加任务次数限制
        );
        $outJson->code = 500;
    }
    echo json_encode($outJson);
}


/**
 * 更新模板
 */
if($uri == "/api/admin/template/update"){
    $postJson = json_decode(file_get_contents("php://input"));
    $id = $postJson->id;
    
    // 如果只更新任务限制
    if(isset($postJson->user_task_limit) && count((array)$postJson) === 2) {
        $user_task_limit = intval($postJson->user_task_limit);
        if($user_task_limit < 0) {
            $outJson->msg = "任务限制次数不能小于0";
            $outJson->code = 400;
            echo json_encode($outJson);
            exit;
        }
        
        $cnSql->update_json("templates", array(
            'user_task_limit' => $user_task_limit
        ), "id = $id");
        
        $outJson->msg = "任务限制更新成功";
        $outJson->code = 200;
        echo json_encode($outJson);
        exit;
    }

    //如果只更新is_open
    if(isset($postJson->is_open) && count((array)$postJson) === 2) {
        $is_open = intval($postJson->is_open);
        $cnSql->update_json("templates", array('is_open' => $is_open), "id = $id");
        $outJson->msg = "模板状态更新成功";
        $outJson->code = 200;
        echo json_encode($outJson);
        exit;
    }
    
    $name = $postJson->name;
    $pictures_count = $postJson->pictures_count;
    $sample_data = $postJson->sample_data;
    $input_structure = $postJson->input_structure;
    $duration = $postJson->duration;
    $regex = $postJson->regex;
    $category_id = $postJson->category_id;
    $template_data = $postJson->template_data;
    $price = isset($postJson->price) ? intval($postJson->price) : 0; // 添加价格字段
    $switch_reasons = $postJson->switch_reasons;
    $regex = str_replace('\\', '\\\\', $regex);
    $template_data = str_replace('\\', '\\\\', $template_data);
    $user_task_limit = intval($postJson->user_task_limit) ? intval($postJson->user_task_limit) : 0;
    $is_open = isset($postJson->is_open) ? intval($postJson->is_open) : 0;
    // 验证图片数量
    if(!is_numeric($pictures_count) || $pictures_count < 0 || $pictures_count > 999) {
        $outJson->msg = "图片数量必须是0-999之间的数字";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 防SQL注入
    $name = addslashes($name);
    
    // 验证输入结构是否为有效JSON
    if(!empty($input_structure)) {
        json_decode($input_structure);
        if(json_last_error() !== JSON_ERROR_NONE) {
            $outJson->msg = "输入结构必须是有效的JSON格式";
            $outJson->code = 400;
            echo json_encode($outJson);
            exit;
        }
    }

    // 验证切换原因是否为有效JSON
    if(!empty($switch_reasons)) {
        json_decode($switch_reasons);
        if(json_last_error() !== JSON_ERROR_NONE) {
            $outJson->msg = "切换原因必须是有效的JSON格式";
            $outJson->code = 400;
            echo json_encode($outJson);
            exit;
        }
    }

    $cnSql->update_json("templates", array(
        'pictures_count' => $pictures_count,
        'sample_data' => $sample_data,
        'input_structure' => $input_structure,
        'duration' => $duration,
        'category_id' => $category_id,
        'switch_reasons' => $switch_reasons, // 添加切换原因
        'regex' => $regex,
        'is_open' => $is_open,
        'template_data' => $template_data,
        'price' => $price, // 添加价格字段
        'user_task_limit' => $user_task_limit // 添加任务次数限制
    ),"id = $id");
    
    $outJson->msg = "模板更新成功";
    $outJson->code = 200;

    echo json_encode($outJson);
}

/**
 * 获取模板列表
 */
if($uri == "/api/admin/templates"){
    $search = isset($_GET['search']) ? $_GET['search'] : "";
    $sql = $cnSql->read_all("templates", "name LIKE '%$search%'");
    // 统计每个模板对应的审核状态数量
    foreach($sql as &$template) {
        $template_id = $template['id'];
        $stats = $cnSql->custom("SELECT 
            SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as unused,
            SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as occupied,
            SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as pending,
            SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) as approved,
            SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) as rejected,
            SUM(CASE WHEN status = 5 THEN 1 ELSE 0 END) as abnormal
        FROM releases WHERE template_id = $template_id")[0];
        
        $template['stats'] = array(
            'unused' => intval($stats['unused']), // 未使用
            'occupied' => intval($stats['occupied']), // 占用中
            'pending' => intval($stats['pending']), // 已提交审核
            'approved' => intval($stats['approved']), // 审核通过
            'rejected' => intval($stats['rejected']), // 审核失败
            'abnormal' => intval($stats['abnormal']) // 爆料数据异常
        );
    }
    // 处理每个模板的价格字段
    foreach($sql as &$template) {
        $template['price'] = intval($template['price']); // 确保价格是数字
    }
    
    $outJson->data = $sql;
    $outJson->code = 200;
    echo json_encode($outJson);
}

/**获取指定模板详情 */
if($uri == "/api/admin/template"){
    $template_id = isset($_GET['id']) ? $_GET['id'] : 0;
    $sql = $cnSql->read_only("templates", "id = $template_id");
    
    // 确保 switch_reasons 字段存在
    if (!isset($sql['switch_reasons'])) {
        $sql['switch_reasons'] = '[]';
    }
    
    $outJson->data = $sql;
    $outJson->code = 200;
    echo json_encode($outJson);
}

/**
 * 统计爆料数量
 */
if($uri == "/api/admin/template/stats"){
    $date_range = $_GET['date_range'];
    if($date_range == "today"){
        $date_range = "1";
    }else if($date_range == "week"){
        $date_range = "7";
    }else if($date_range == "month"){
        $date_range = "30";
    }else if($date_range == "all"){
        $date_range = "-1";
    }
    $template_id = isset($_GET['template_id']) ? $_GET['template_id'] : 0;
    if($template_id == 0){
        $outJson->msg = "模板ID不能为空";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }
    if($date_range == "-1"){    
        $time_where = "1=1";
    }else{
        $time_where = "create_time >= DATE_SUB(CURDATE(), INTERVAL $date_range DAY)";
    }
    $sql = $cnSql->total("submit_details", "template_id = $template_id AND $time_where");
    $outJson->count = $sql;
    $outJson->code = 200;
    echo json_encode($outJson);
    exit;
  
}

/**
 * 导出模板数据
 */
if($uri == "/api/admin/template/export"){
    $template_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    if(!$template_id) {
        $outJson->msg = "模板ID不能为空";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 获取模板信息
    $template = $cnSql->read_only("templates", "id = $template_id");
    if(!$template) {
        $outJson->msg = "模板不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 获取所有非待处理的任务
    $releases = $cnSql->custom("SELECT r.*, 
            d.out_structure, 
            d.image_paths,
            u.user as username
        FROM releases r
        LEFT JOIN submit_details d ON r.id = d.task_id
        LEFT JOIN users u ON d.user_id = u.id
        WHERE r.template_id = $template_id 
        AND r.status != 0
        ORDER BY r.create_time DESC
    ");

    // 设置header为CSV文件
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $template['name'] . '_' . date('YmdHis') . '.csv"');

    // 创建一个输出流
    $output = fopen('php://output', 'w');
    
    // 添加 UTF-8 BOM，解决Excel打开中文乱码
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

    // 写入表头
    fputcsv($output, array(
        '任务ID',
        '状态',
        '数据',
        '提交用户',
        '提交数据',
        '图片链接',
        '创建时间'
    ));

    // 写入数据
    foreach($releases as $release) {
        $status_text = '';
        switch($release['status']) {
            case 1: $status_text = '进行中'; break;
            case 2: $status_text = '待审核'; break;
            case 3: $status_text = '已通过'; break;
            case 4: $status_text = '已拒绝'; break;
            case 5: $status_text = '异常'; break;
            default: $status_text = '未知'; break;
        }

        fputcsv($output, array(
            $release['id'],
            $status_text,
            $release['data'],
            $release['username'],
            $release['out_structure'],
            $release['image_paths'],
            $release['create_time']
        ));
    }

    // 关闭输出流
    fclose($output);
    exit;
}

/**
 * 下载模板数据
 */
if($uri == "/api/admin/template/download"){
    $template_id = isset($_GET['template_id']) ? intval($_GET['template_id']) : 0;
    $status = isset($_GET['status']) ? $_GET['status'] : null;
    $date = isset($_GET['date']) ? $_GET['date'] : null;
    $start_date = isset($_GET['start_date']) ? $_GET['start_date'] : null;
    $end_date = isset($_GET['end_date']) ? $_GET['end_date'] : null;

    // 获取模板信息
    $template = $cnSql->read_only("templates", "id = $template_id");
    if(!$template) {
        exit("模板不存在");
    }

    // 构建查询条件
    $where = "r.template_id = $template_id";
    if($status !== null) {
        $where .= " AND r.status = '$status'";
    }
    if($date) {
        $where .= " AND DATE(r.create_time) = '$date'";
    } else if($start_date && $end_date) {
        $where .= " AND DATE(r.create_time) BETWEEN '$start_date' AND '$end_date'";
    }

    // 获取数据
    $data = $cnSql->custom("SELECT r.*, sd.image_paths, sd.user_id 
        FROM releases r 
        LEFT JOIN submit_details sd ON r.id = sd.task_id 
        WHERE $where ORDER BY r.id DESC");

    // 设置CSV头
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $template['name'] . '_' . date('YmdHis') . '.csv"');

    // 输出CSV
    $output = fopen('php://output', 'w');
    // 写入BOM，解决中文乱码
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    
    // 写入表头
    $headers = array('ID', '内容', '状态', '创建时间');
    // 添加图片列
    $max_images = 0;
    foreach($data as $row) {
        if(!empty($row['image_paths'])) {
            $images = json_decode($row['image_paths'], true);
            $max_images = max($max_images, count($images));
        }
    }
    for($i = 1; $i <= $max_images; $i++) {
        $headers[] = "图片" . $i;
    }
    // 如果有状态5的数据,添加异常原因列
    if($status == 5) {
        $headers[] = "异常原因";
    }
    fputcsv($output, $headers);
    
    // 写入数据
    foreach($data as $row) {
        $status_text = '';
        switch($row['status']) {
            case 0: $status_text = '未开始'; break;
            case 1: $status_text = '进行中'; break;
            case 2: $status_text = '待审核'; break;
            case 3: $status_text = '已通过'; break;
            case 4: $status_text = '已拒绝'; break;
            case 5: $status_text = '异常'; break;
            default: $status_text = '未知'; break;
        }

        $csv_row = array(
            $row['id'],
            $row['data'],
            $status_text,
            $row['create_time']
        );

        // 添加图片路径
        $images = array();
        if(!empty($row['image_paths'])) {
            $images = json_decode($row['image_paths'], true);
            if(!is_array($images)) {
                $images = array();
            }
        }
        for($i = 0; $i < $max_images; $i++) {
            $csv_row[] = isset($images[$i]) ? $images[$i]['url'] : '';
        }

        // 如果状态是5,添加异常原因
        if($row['status'] == 5) {
            $csv_row[] = $row['switch_reason'];
        }

        fputcsv($output, $csv_row);
    }
    
    fclose($output);
    exit;
}

/**
 * 获取可下载数据数量
 */
if($uri == "/api/admin/template/download/count"){
    $template_id = isset($_GET['template_id']) ? intval($_GET['template_id']) : 0;
    $status = isset($_GET['status']) ? $_GET['status'] : null;
    $date = isset($_GET['date']) ? $_GET['date'] : null;
    $start_date = isset($_GET['start_date']) ? $_GET['start_date'] : null;
    $end_date = isset($_GET['end_date']) ? $_GET['end_date'] : null;

    // 构建查询条件
    $where = "template_id = $template_id";
    if($status !== null) {
        $where .= " AND status = '$status'";
    }
    if($date) {
        $where .= " AND DATE(create_time) = '$date'";
    } else if($start_date && $end_date) {
        $where .= " AND DATE(create_time) BETWEEN '$start_date' AND '$end_date'";
    }

    // 获取数量
    $count = $cnSql->total("releases", $where);

    $outJson->count = $count;
    $outJson->where = $where;
    $outJson->code = 200;
    echo json_encode($outJson);
    exit;
}